package concept.chapter7.backedcollections;

import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * A concept proven class proving that: 
 * <p>
 * 1. Both original and copy point to the same <code>Collection</code> object;<br>
 * 2. Any operations on the copy affects the original;<br>
 * 3. Operations on sections shadowed by the copy on the original affect both;<br>
 * 4. Operations on sections out of range covered by the copy on the original do;<br>
 * NOT affect the copy but the original only.<br> 
 * 
 * @author kan.sun
 *
 */
public class BackedCollections
{
	public static void main(String[] args)
	{
		TreeMap<String, String> map = new TreeMap<String, String>();
		map.put("a", "ant");
		map.put("d", "dog");
		map.put("h", "horse");
		
		SortedMap<String, String> submap = map.subMap("b", "g");
		System.out.println("Original: "+map+"\nSorted copy: "+submap+"\n");
		
		map.put("b", "bat");
		submap.put("f", "fish");
		
		map.put("r", "raccon");
		System.out.println("Original: "+map+"\nSorted copy: "+submap+"\n");
		
		//pick up the head map
		NavigableMap<String, String> nSubMap = map.subMap("a", true, "f", false);
		System.out.println("Original: "+map+"\nNevigable copy: "+nSubMap+"\n");
		
		//remove the head on the original
		//the copy will be affected
		map.pollFirstEntry();
		System.out.println
		(
			"Polled original: "+map+
			"\nNevigable copy: "+nSubMap+
			"\n"
		);
		
		//remove the tail on the copy
		//the original will be affected
		nSubMap.pollLastEntry();
		System.out.println
		(
				"Polled original: "+map+
				"\nNevigable copy: "+nSubMap+
				"\n"
		);

		//remove the tail on the original
		//the copy will NOT be affected
		map.pollLastEntry();
		System.out.println
		(
				"Polled original: "+map+
				"\nNevigable copy: "+nSubMap+
				"\n"
		);
	}

}
